package org.ezplatform.office.meeting.info.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.office.meeting.info.entity.*;
import org.ezplatform.util.GlobalConstant;
import org.ezplatform.office.meeting.info.dao.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.quanshi.openapi.QsAPI;
import com.quanshi.openapi.QsUtil;
import com.quanshi.openapi.entity.QsAccount;
import com.quanshi.openapi.entity.QsConfParty;
import com.quanshi.openapi.entity.QsConfSetting;
import com.quanshi.openapi.entity.QsConsts;
import com.quanshi.openapi.entity.QsResponse;
/**
 * 全时会议用户
 * @author sj
 *
 */
@Service("QSUserService")
@Transactional
public class QSUserService extends BaseService<QSUser, String>{
	
     private final Logger logger = LoggerFactory.getLogger(QSUserService.class);
     
    // 产品ID, 5:MAX 2:PC2.0预约 3:PC2.0即时 4:PC2.0统一
 	private static final String appId = "6";
 	
 	private static String p12Path =  GlobalConstant.getConfig("qs.client");// "D:\\workspacests3.9.4\\openapi-sample\\zhongkeyungu.client.p12";
 	private static String trustStorePath =GlobalConstant.getConfig("qs.server");//"D:\\workspacests3.9.4\\openapi-sample\\server.truststore";
 	private static String emailstr =GlobalConstant.getConfig("qs.email");//qusnshi.com
	
     @Autowired
 	 private QSUserDao dao;

 	 @Override
 	 protected JpaBaseDao<QSUser, String> getEntityDao() {
 		return this.dao;
 	 }
 	 
 	 public void login(String userName, String password, boolean launchClient) {
    	logger.debug("QsConsts.VERSIONMODE_SIMPLE:"+QsConsts.VERSIONMODE_SIMPLE);
		QsResponse response = QsAPI.login(userName, password, QsConsts.VERSIONMODE_SIMPLE, launchClient);
		if (response.isSuccess()) { 
			String result = response.getResult();
			// 打印字符串格式结果
			logger.debug("登陆成功, result=" + result);
			// 利用QsUtil.java 转换JSON格式为 Map<String, Object>
			Map<String, Object> resultMap = QsUtil.jsonSTM(result);
			logger.debug("用户状态:" + resultMap.get("userStatus"));
			logger.debug("用户Id:" + resultMap.get("userId"));
			logger.debug("用户登陆账号:" + resultMap.get("userName"));
			logger.debug("用户姓名:" + resultMap.get("name"));
			logger.debug("用户电话:" + resultMap.get("mobileNumber"));
			logger.debug("用户身份:" + resultMap.get("identity"));
			logger.debug("用户所属站点:" + resultMap.get("siteUrl"));
			logger.debug("其他属性...");
		} else {
			logger.debug("登陆失败, " + response.getStatus());
			// 状态码请参考OpenApi错误返回值
			logger.debug("状态码:" + response.getStatus());
		}
	}
	
 	 /**
 	  * 创建全时会议账号
 	  * @param userName
 	  * @param password
 	  * @param hostUserId
 	  * @param company
 	  * @param oalogin_name
 	  * @param oauser_name
 	  * @param oauserId
 	  * @param emailacc
 	  * @return
 	  */
 	public Map createAccount(String userName, 
			                         String password, 
			                         String hostUserId,
			                         String company,
			                         String oalogin_name,
			                         String oauser_name,
			                         String oauserId,
			                         String emailacc) {
		
		Map resultMap = null;
		QsAccount acc = new QsAccount();
		acc.setAccountType("1");
		acc.setUserCompany(company);
		
		acc.setUserEmail(emailacc);
		acc.setUserMobile("");
		acc.setUserName(oauser_name);
		acc.setHostUserId(hostUserId);
		QsResponse response1 = QsAPI.createAccount(userName, password, acc);
		if (response1.isSuccess()) {
			String result = response1.getResult();
			// 打印字符串格式结果
			logger.error("创建用户成功, result=" + result);
			// 利用QsUtil.java 转换JSON格式为 Map<String, Object>
			resultMap = QsUtil.jsonSTM(result);
//			logger.info("userId:" + resultMap.get("userId"));//{"userId":17540720,"passwd":"sho9962"}
		} else {
			logger.error("创建用户失败, " + response1.getStatus());
		}
		return resultMap;
		
	}
	
 	/**
 	 * 预约会议
 	 * @param userId
 	 * @param title
 	 * @param length
 	 * @param startTime
 	 * @param siteUrl
 	 * @return
 	 */
	public Map<String, Object> reservConference(String userId, 
			                                    String title, 
			                                    String length, 
			                                    Date startTime,
			                                    String siteUrl) {
		
		logger.debug("------------------------reservConference-------------------------");
//		String siteUrl = "zhongkeyungu.quanshi.com";
		// 请确保证书路径正确
		QsAPI.init(appId, siteUrl, p12Path, trustStorePath);
					
		QsConfSetting qcs = new QsConfSetting();
		List<QsConfParty> list = new ArrayList<QsConfParty>();
		int intlength = Integer.parseInt(length);
		logger.debug("-userId:"+userId);
		logger.debug("-title:"+title);
		logger.debug("-intlength:"+intlength);
		logger.debug("-startTime:"+startTime);
		QsResponse response1 = QsAPI.reservConference(userId, title, intlength, startTime, qcs, list);
		Map<String, Object> resultMap = new HashMap();
		if (response1.isSuccess()) {
			String result = response1.getResult();
			logger.debug("预约会议成功, result=" + result);
			//result={"attendeeJoinUrl":"http://m.qsh1.cn/k/7Ao9k5H","billingCode":"79438785","billingcode":"79438785","conferenceId":"2550418","conferenceTitle":"网络会议","creatorAccount":"729352717@qq.com","creatorName":"JSH","currentTime":"2020-04-07 15:29:32","dTitle":"网络会议","desc":"参会人密码：8694608875","email_notify":false,"endTime":"2020-04-15 00:30:00","endTimeUnix":0,"from":"","h323Ip":["119.253.82.164"],"host":"JSH","hostConferenceUrl":"http://m.qsh1.cn/k/qT6YHNa","hostMobile":"15155939704","hostname":"JSH","informType":3,"length":30,"location":"","pcode1":"8694599741","pcode2":"8694608875","startTime":"2020-04-15 00:00:00","startTimeUnix":0,"status":1,"title":"邀请您参加JSH的会议","usedConfTickets":0,"userId":17540720,"wcallUrl":"https://dwz.cn/yP4rgDsw","attendeeJoinLongUrl":"http://m.qsh1.cn/k/7Ao9k5H","hostConferenceLongUrl":"http://m.qsh1.cn/k/qT6YHNa"}
			resultMap = QsUtil.jsonSTM(result);
			resultMap.put("success", "0");
		}else {
			String err = "预约会议失败, " + response1.getStatus();
			logger.debug(err);
			resultMap = new HashMap();
			resultMap.put("success", "-1");
			resultMap.put("err", err);
		}
		return resultMap;
	}
	
	/**
	 * 修改预约会议
	 * @param conferenceId
	 * @param userId
	 * @param title
	 * @param length
	 * @param startTime
	 * @param siteUrl
	 * @return
	 */
	public Map<String, Object> modifyConference(String conferenceId, 
			                                    String userId, 
			                                    String title, 
			                                    String length, 
			                                    Date startTime,
                                                String siteUrl) {
		// 请确保证书路径正确
		QsAPI.init(appId, siteUrl, p12Path, trustStorePath);
					
		QsConfSetting qcs = new QsConfSetting();
		List<QsConfParty> list = new ArrayList<QsConfParty>();
		int intlength = Integer.parseInt(length);
		QsResponse response1 = QsAPI.modifyConference(userId, conferenceId, title, intlength, startTime, qcs, list) ;
		Map<String, Object> resultMap = new HashMap();
		if (response1.isSuccess()) {
			String result = response1.getResult();
			logger.debug("修改预约会议成功, result=" + result);

            resultMap = QsUtil.jsonSTM(result);
			resultMap.put("success", "0");
		}else {
			String err = "修改预约会议失败, " + response1.getStatus();
			logger.debug(err);
			resultMap = new HashMap();
			resultMap.put("success", "-1");
			resultMap.put("err", err);
		}
		return resultMap;
	}
	
	/**
	 * 取消预约会议
	 * @param conferenceId
	 * @param siteUrl
	 * @return
	 */
	public Map<String, Object> cancelConference(String conferenceId,
			                                    String qsuserId,
                                                String siteUrl) {
		
		// 请确保证书路径正确
		QsAPI.init(appId, siteUrl, p12Path, trustStorePath);
		Long userId = Long.parseLong(qsuserId); 
		QsResponse response1 = QsAPI.cancelConference(conferenceId,userId) ;
		Map<String, Object> resultMap=null;
		if (response1.isSuccess()) {
			String result = response1.getResult();
			logger.debug("取消预约会议成功, result=" + result);
			
			resultMap = QsUtil.jsonSTM(result);
			logger.debug(":" + resultMap);
		}else {
			logger.debug("取消预约会议失败, " + response1.getStatus());
			// 状态码请参考OpenApi错误返回值
			logger.debug("状态码:" + response1.getStatus());
		}
		return resultMap;
	}
    
	public void joinConference(String conferenceId, String pcode, String name) {
		QsConfSetting qcs = new QsConfSetting();
		List<QsConfParty> list = new ArrayList<QsConfParty>();
		QsResponse response1 = QsAPI.joinConference(conferenceId, pcode, name, name);
		if (response1.isSuccess()) {
			String result = response1.getResult();
			logger.debug("查询成功, result=" + result);
			//result={"attendeeJoinUrl":"http://m.qsh1.cn/k/7Ao9k5H","billingCode":"79438785","billingcode":"79438785","conferenceId":"2550418","conferenceTitle":"网络会议","creatorAccount":"729352717@qq.com","creatorName":"JSH","currentTime":"2020-04-07 15:29:32","dTitle":"网络会议","desc":"参会人密码：8694608875","email_notify":false,"endTime":"2020-04-15 00:30:00","endTimeUnix":0,"from":"","h323Ip":["119.253.82.164"],"host":"JSH","hostConferenceUrl":"http://m.qsh1.cn/k/qT6YHNa","hostMobile":"15155939704","hostname":"JSH","informType":3,"length":30,"location":"","pcode1":"8694599741","pcode2":"8694608875","startTime":"2020-04-15 00:00:00","startTimeUnix":0,"status":1,"title":"邀请您参加JSH的会议","usedConfTickets":0,"userId":17540720,"wcallUrl":"https://dwz.cn/yP4rgDsw","attendeeJoinLongUrl":"http://m.qsh1.cn/k/7Ao9k5H","hostConferenceLongUrl":"http://m.qsh1.cn/k/qT6YHNa"}
		}else {
			logger.debug("查询失败, " + response1.getStatus());
			// 状态码请参考OpenApi错误返回值
			logger.debug("状态码:" + response1.getStatus());
		}
	}
 	 
 	 /**
 	  * 保存信息
 	  * @param list
 	  * @return
 	  */
 	 public QSUser saveQSUser(QSUser info) {
 		logger.debug("---saveQSUser--");
 		
		return super.save(info);
	 }
 	 
 	public List<QSUser> saveQSUserList(List<QSUser> list) {
 		logger.error("---saveQSUserList--");
 		
		return super.save(list);
	 }
 	
 	
 	/**
 	 * 获取用户对应全时账号
 	 * @param userId
 	 * @return
 	 */
 	public String getQsUserAcc(String userId) {
    	logger.debug("-----------------getQsUserAcc-------");
        StringBuffer sql = new StringBuffer("select qsuserId from oa_meeting_qsuser "
        		+ " where userAccount=(select login_name from sys_user where id='"+userId+"') ");
        List<Map> list = super.findByListNativeQuery(sql.toString(), "");
        if(list!=null&&list.size()>0) {
           return list.get(0).get("qsuserId")+"";
        }else {
        	return "";
        }
    }
 	
}
